<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution housing-table">
        <basic-container>
            <avue-crud ref="crud"
                        v-model="form"
                        :row-class-name="setCellClass"
                       :page.sync="page"
                       :data="tableData"
                       :span-method="spanMethod"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="rowDel">
                       <template slot="menuLeft">
                           <el-button
                                icon="el-icon-download"
                                size="small"
                                type="primary"
                                @click="listexportReport">导出</el-button>
                       </template>
                       <template
                            slot="areaId"
                            slot-scope="scope">
                            {{ scope.row.address }}
                        </template>
                        <template
                            slot="index"
                            slot-scope="scope">
                            {{ scope.row.index }}
                        </template>
                         <template
                            slot="roomNumber"
                            slot-scope="scope">
                            <!-- <span class="bed-number-span" @click="view(scope.row)">{{ scope.row.roomNumber }}</span> -->
                            <span>{{ scope.row.roomNumber }}</span>
                        </template>
                         <template
                            slot="bedNumber"
                            slot-scope="scope">
                            <span class="bed-number-span" @click="viewBed(scope.row)">{{ scope.row.bedNumber }}</span>
                        </template>
                         <template
                            slot="sharingArea"
                            slot-scope="scope">
                            {{ scope.row.bedList && scope.row.bedList.length ? scope.row.sharingArea1:  scope.row.sharingArea}}
                        </template>
                         <template
                            slot="roomArea"
                            slot-scope="scope">
                             {{ scope.row.bedList && scope.row.bedList.length ? scope.row.roomArea1:  scope.row.roomArea}}
                        </template>
                         <template
                            slot="rentArea"
                            slot-scope="scope">
                             {{ scope.row.bedList && scope.row.bedList.length ? scope.row.rentArea1:  scope.row.rentArea}}
                        </template>
                         <template
                            slot="defaultRent"
                            slot-scope="scope">
                             {{ scope.row.bedList && scope.row.bedList.length ? scope.row.defaultRent1:  scope.row.defaultRent}}
                        </template>
                        <template
                            slot="areaIdForm"
                            slot-scope="scope">
                            <el-cascader
                                ref="areaIdRef"
                                v-model="form.areaId"
                                :props="props"
                                :options="treeData"
                                placeholder="请选择所属区域">
                            </el-cascader>
                        </template>
                        <template
                            slot="bedNumberForm"
                            slot-scope="scope">
                            {{ form.bedStr}}
                        </template>
                         <template
                            slot="operate"
                            slot-scope="scope">
                            <el-button type="text"
                              size="small"
                              @click="view(scope.row)">查看</el-button>
                            <el-button type="text"
                              size="small"
                              @click="edit(scope.row)">编辑</el-button>
                            <el-button type="text"
                              size="small"
                              @click="rowDel(scope.row)">删除</el-button>
                            <el-button type="text"
                              size="small"
                              @click="showDialog(scope, '1')">配置</el-button>
                            <!-- <el-button type="text"
                              size="small"
                              @click="showDialog(scope, '2')">维修记录</el-button> -->
                            <el-button type="text"
                              size="small"
                              @click="showDialog(scope, '3')">申请记录</el-button>
                            <el-button type="text"
                              size="small"
                              @click="showDialog(scope, '4')">退房记录</el-button>
                            <el-button type="text"
                              size="small"
                              @click="changeType(scope)">类型转换</el-button>
                            <el-button type="text"
                              size="small"
                              @click="showDialog(scope, '5')">转换记录</el-button>
                        </template>
            </avue-crud>
        </basic-container>
        <el-dialog
            :visible.sync="modal1"
            v-if="modal1"
            :title="title"
            width="1200px"
            top="2vh"
            :close-on-click-modal="false"
            append-to-body>
            <asset :areaId="areaId" v-if="type == '1'"></asset>
            <housing-record :housingId="housingId" :bedId="bedId" v-if="type == '3'"></housing-record>
            <handover :housingId="housingId" v-if="type == '4'"></handover>
            <housing-change :housingId="housingId" v-if="type == '5'"></housing-change>
        </el-dialog>
         <el-dialog
            :visible.sync="modal2"
            v-if="modal2"
            title="查看"
            width="60%"
            top="15vh"
            :close-on-click-modal="false"
            append-to-body>
            <avue-form ref="form2" class="avue--detail" v-model="form2" :option="option" >
            </avue-form>
        </el-dialog>
    </div>
</template>

<script>
    import {fetchList, housingchange, addObj, putObj, delObj, exportObj} from '@/api/housing/housing'
    import { fetchTree, fetchList as fetchList1 } from '@/api/admin/sysarea'
    import asset from '@/views/asset/asset/index'
    import handover from '@/views/housing/housinghandover/index'
    import housingRecord from '@/views/housing/oahousingbill/housingBiz'
    import housingChange from '@/views/housing/housingchange/index'
    import {tableOption} from '@/const/crud/housing/housing'
    import {tableOption1} from '@/const/crud/housing/housingbed'
    import {mapGetters} from 'vuex'

    export default {
        components: {
            asset,
            handover,
            housingRecord,
            housingChange
        },
        props: ['flag'],
        name: 'housing',
        data() {
            return {
                form2: {},
                areaId: '',
                housingId: '',
                bedId: '',
                searchForm: {},
                tableData: [],
                treeData: [],
                type: '',
                form2: {},
                props:{
                    label: 'name',
                    value: 'id',
                    emitPath: false
                },
                modal1: false,
                modal2: false,
                arr: [],
                form:{},
                flList:[],
                title: '资产配置',
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                option: tableOption1,
                tableOption: tableOption
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permissions.act_housing_add, false),
                    delBtn: this.vaildData(this.permissions.act_housing_del, false),
                    editBtn: this.vaildData(this.permissions.act_housing_edit, false)
                };
            }
        },
        mounted() {
            this.tableOption.height = this.tableHeight() + 10
        },
        created() {
            this.init()
            this.eventBusHandle()
            var field_operate = this.findObject(this.tableOption.column,'operate')
            if (this.flag && this.flag === 'bill') {
                field_operate.hide = true
                this.tableOption.addBtn = false
            } else {
                field_operate.hide = false
                this.tableOption.addBtn = true
            }
        },
        methods: {
            eventBusHandle () {
                const _this = this
                eventBus1.$off('changeHeight').$on('changeHeight', function (data) {
                    setTimeout(function(){
                        if (document.getElementsByClassName("el-table")[0]) {
                            document.getElementsByClassName("el-table")[0].style.height = _this.tableHeight() + 10 + 'px'
                        }
                    }, 500)
                })
            },
            listexportReport() {
                exportObj(this.searchForm).then(response => {
                    const link = document.createElement("a");
                    let blob = new Blob([response.data]);
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    var fileName = response.headers["content-disposition"]
                        .split(";")[1]
                        .split("filename=")[1];
                    link.setAttribute("download", decodeURIComponent(fileName));
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }).catch(() => {
                    this.$message.error("导出失败");
                });
            },
            init() {
                fetchTree().then(response => {
                    this.treeData = response.data.data
                })
                fetchList1({current: 1, size:1000}).then(response => {
                    this.flList = response.data.data.records
                })
            },
            view(row) {
                if (row.bedList && row.bedList.length > 0) {
                    let bedList = []
                    row.bedList.map(item => {
                        bedList.push(item.bedNumber)
                    })
                    row.bedStr = bedList.join(',')
                } else {
                    row.bedStr = ''
                }
                this.$refs.crud.rowView(row)
            },
            viewBed(row) {
                let att = Object.assign({}, row)
                att.rentArea = att.rentArea1
                att.defaultRent = att.defaultRent1
                att.sharingArea = att.sharingArea1
                att.roomArea = att.roomArea1
                att.status = att.status1
                this.form2 = att
                this.modal2 = true
            },
            edit(row) {
                this.$refs.crud.rowEdit(row)
            },
            changeType(scope) {
                let self = this
                this.$confirm('是否确认类型转换?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    housingchange({
                        housingId: scope.row.housingId
                    }).then(response => {
                        self.$message.success('转换成功')
                        self.getList(self.page)
                    })
                })
            },
            showDialog (scope, type) {
                this.type = type
                if (type === '1') {
                    this.title = '资产配置'
                } else if(type === '3') {
                    this.title = '申请记录'
                } else if (type === '4') {
                    this.title = '退房记录'
                } else if(type === '5') {
                    this.title = '转换记录'
                }
                this.areaId = scope.row.areaId
                this.housingId = scope.row.housingId
                this.bedId = scope.row.bedId
                this.modal1 = true
            },
            setCellClass ({row, column, rowIndex, columnIndex}) {
                // 给当前鼠标移入的合并行第一行加上样式名
                if (row.status1 === '0') {
                    return 'cellClass'
                }
            },
            spanMethod({ row, column, rowIndex, columnIndex }) {
                if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2|| columnIndex === 15 || columnIndex === 16 || columnIndex === 11 || columnIndex === 12 || columnIndex === 13 || columnIndex === 14|| columnIndex === 23  || columnIndex === 22  || columnIndex === 21) {
                    if (row.typeIndex) { // 如果有值,说明需要合并
                        return [row.typeIndex, 1]
                    } else return [0, 0]
                }
            },
            getFlName(id) {
                let list =  this.flList.filter(item => {
                    return item.categoryId === id
                })
                return list.length > 0 ? list[0].name : ''
            },
            getList(page, params) {
                let _this = this
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    let getTable = []
                    response.data.data.records.map((item, index) => {
                        if (item.bedList && item.bedList.length > 0) {
                            item.bedList.map((citem, i) => {
                                const obj = Object.assign({}, item)
                                obj.bedNumber = citem.bedNumber
                                obj.sharingArea1 = citem.sharingArea
                                obj.roomArea1 = citem.roomArea
                                obj.rentArea1 = citem.rentArea
                                obj.residentRealname = citem.residentRealname
                                obj.residentPhone = citem.residentPhone
                                obj.residentSex = citem.residentSex
                                obj.residentDeptName = citem.residentDeptName
                                obj.residentType = citem.residentType
                                obj.residentPostRank = citem.residentPostRank
                                obj.bedId = citem.bedId
                                obj.defaultRent1 = citem.defaultRent
                                obj.status1 = citem.status
                                obj.gas = citem.gas
                                obj.electricity = citem.electricity
                                obj.water = citem.water
                                obj.index = index + 1
                                if (i === 0) {
                                    obj.typeIndex = item.bedList.length
                                }
                                getTable.push(obj)
                            })
                        } else {
                            item.status1 = item.status
                            item.index = index + 1
                            item.typeIndex = 1
                            getTable.push(item)
                        }
                    })
                    this.tableData = getTable
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            rowDel: function (row, index) {
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.housingId)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            handleUpdate: function (row, index, done,loading) {
                let params= {}
                let choseArea = this.$refs['areaIdRef'].getCheckedNodes()[0]
                params.address = choseArea.pathLabels.join('')
                params.housingId = row.housingId
                params.areaId = row.areaId
                params.roomNumber = row.roomNumber
                params.housingType = row.housingType
                params.structure = row.structure
                params.toward = row.toward
                params.constructionArea = row.constructionArea
                params.usageArea = row.usageArea
                params.rentArea = row.rentArea
                params.defaultRent = row.defaultRent
                params.propertyNumber = row.propertyNumber
                params.property = row.property
                params.status = row.status
                params.remark = row.remark
                params.cover = row.cover
                params.sort = row.sort
                putObj(params).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                let params= {}
                let choseArea = this.$refs['areaIdRef'].getCheckedNodes()[0]
                params.address = choseArea.pathLabels.join('')
                params.housingId = row.housingId
                params.areaId = row.areaId
                params.roomNumber = row.roomNumber
                params.housingType = row.housingType
                params.structure = row.structure
                params.toward = row.toward
                params.constructionArea = row.constructionArea
                params.usageArea = row.usageArea
                params.rentArea = row.rentArea
                params.defaultRent = row.defaultRent
                params.propertyNumber = row.propertyNumber
                params.property = row.property
                params.status = row.status
                params.remark = row.remark
                params.cover = row.cover
                params.sort = row.sort
                addObj(params).then(data => {
                    this.$message.success('添加成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>
<style lang="scss">
.housing-table{
    .cellClass {
        td {
            background-color: #7bc395 !important;
            .el-button--text{
                color: #606266;
            }
        }
    }
    .hover-row{
        td {
            background-color: #7bc395 !important;
            .el-button--text{
                color: #606266;
            }
        }
    }
    // .el-table__fixed-right::before{
    //     height: 0;
    // }
    // ::-webkit-scrollbar:horizontal{
    //     height: 15px;
    // }
    // ::-webkit-scrollbar-thumb:horizontal {
    //     border-radius: 10px !important;
    //     -webkit-box-shadow: inset 0 0 6px #7bc395 !important;
    //     background-color: #7bc395 !important;
    // }
}
.bed-number-span{
    color: #409EFF;
    cursor: pointer;
    &:hover{
        text-decoration: underline;
    }
}
</style>